//
//  FactoryMessageViewController.m
//  MagictoLane
//
//  Created by huayu01 on 2017/12/4.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "FactoryMessageViewController.h"
#import "FactoryMessageTableViewCell.h"
#import "TZImagePickerController.h"
#import "CloseAreaViewController.h"
#import <AVKit/AVKit.h>
#import <Photos/PHPhotoLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import "FactoryIntroductionViewController.h"
#import "KSPhotoBrowser.h"
#import "FactoryTypeViewController.h"
#import "FactoryMessageModel.h"
#import "FactoryImgsModel.h"
#import "FactoryProductModel.h"
#import "UserModel.h"
#import "FactoryCategoryModel.h"
#import "FactoryMapViewController.h"

//自定义的枚举
typedef NS_ENUM(NSInteger, ChosePhontType) {
    ChosePhontTypeAlbum,  //相册
    ChosePhontTypeCamera   //相机
};

@interface FactoryMessageViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate, TZImagePickerControllerDelegate,UITextViewDelegate>
{
    CGFloat scrollViewOffSetY;
    CGFloat remainingDistanceY;
    CGFloat beforeMigrationY;
    NSMutableArray *photoArr;
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    UILabel *tipLabel;
}
@property (nonatomic, strong) UITableView *factoryMessageTableView;
@property (nonatomic, strong) NSMutableArray *messageNameArr;
@property (nonatomic, strong) NSMutableArray *detailMessageNameArr;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) UIImageView *userIcon;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, strong) NSMutableArray *imageStringArr;
@property (nonatomic, copy) NSString *addressStr;
@property (nonatomic, strong) UICollectionView *pictureCollectionView;
@property (nonatomic, copy) NSString *productId;
@property (nonatomic, copy) NSString *areaId;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end

@implementation FactoryMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self requestUserMessage];
    [self setupUI];
    [self setupFactoryMessageTableView];
    [self requestFactoryMessage];
    _areaId = @"";
    _productId = @"";
    self.imageStringArr = [NSMutableArray array];
    photoArr = [NSMutableArray array];
    self.imageArr = [NSMutableArray array];
    self.messageNameArr = @[@"公司logo", @"雇主名称", @"ID", @"常用地", @"负责人", @"联系电话",@"雇主定位", @"联系地址"].mutableCopy;
    self.detailMessageNameArr = @[@"", @"", @"", @"", @"", @"", @"", @""].mutableCopy;
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpantanchu:) name:UIKeyboardDidShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)setupUI {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveFactoryMessage)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationItem.title = @"雇主信息";
}

- (void)setupFactoryMessageTableView {
    _factoryMessageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) style:UITableViewStyleGrouped];
    _factoryMessageTableView.delegate = self;
    _factoryMessageTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _factoryMessageTableView.tableHeaderView = view;
    _factoryMessageTableView.tableFooterView = view;
    _factoryMessageTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_factoryMessageTableView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 90 * displaywidth;
    } else {
        return 45 * displaywidth;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    if (indexPath.row == 0) {
        NSInteger logoWidth = 80 * displaywidth;
        if (!_userIcon) {
            _userIcon = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH - logoWidth - 15, (90 * displaywidth - logoWidth) / 2, logoWidth, logoWidth) ImageName:@"zhanwei"];
            _userIcon.backgroundColor = [UIColor cyanColor];
            _userIcon.layer.cornerRadius = logoWidth / 2;
            _userIcon.layer.masksToBounds = YES;
            _userIcon.contentMode = UIViewContentModeScaleAspectFill;
            _userIcon.clipsToBounds = YES;
            [_userIcon setContentScaleFactor:[[UIScreen mainScreen] scale]];
            _userIcon.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserIcon)];
            [_userIcon addGestureRecognizer:tap];
        }
        if (![_detailMessageNameArr[0] isEqualToString:@""]) {
            NSURL *url = [NSURL URLWithString:_detailMessageNameArr[0]];
            [_userIcon sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanwei"]];
        }
        [cell.contentView addSubview:_userIcon];
    } else if (indexPath.row == 3 || indexPath.row == 6){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 7) {
        if (![self.view viewWithTag:indexPath.row + 100]) {
            if (indexPath.row == 7) {
                UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 200 * displaywidth - 33, 0, 200 * displaywidth, 45 * displaywidth)];
                textView.backgroundColor = [UIColor clearColor];
                textView.delegate = self;
                textView.tag = indexPath.row + 100;
                textView.textAlignment = NSTextAlignmentRight;
                textView.textColor = UIColorHexValue(0xB3B3B3);
                textView.font = [UIFont systemFontOfSize:14];
                tipLabel = [ZCControl createLabelWithFrame:CGRectMake(5, 0, textView.frame.size.width-12, 33*displaywidth) Font:14 Text:@"请输入联系地址" Color:UIColorHexValue(0xB3B3B3)];
                tipLabel.textAlignment = NSTextAlignmentRight;
                [textView addSubview:tipLabel];
                [cell.contentView addSubview:textView];
            } else {
                UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 200 * displaywidth - 33, 0, 200 * displaywidth, 45 * displaywidth)];
                textField.backgroundColor = [UIColor clearColor];
                textField.delegate = self;
                textField.tag = indexPath.row + 100;
                textField.textAlignment = NSTextAlignmentRight;
                textField.textColor = UIColorHexValue(0xB3B3B3);
                textField.font = [UIFont systemFontOfSize:14];
                if (indexPath.row == 1) {
                    textField.placeholder = @"请输入工厂名称";
                } else if (indexPath.row == 4) {
                    textField.placeholder = @"请输入负责人";
                } else if (indexPath.row == 5) {
                    textField.placeholder = @"请输入联系电话";
                    textField.keyboardType = UIKeyboardTypePhonePad;
                }
                
                [cell.contentView addSubview:textField];
            }
        }
        UITextField *textField = [self.view viewWithTag:indexPath.row + 100];
        textField.text = _detailMessageNameArr[indexPath.row];
        UITextView *textView = [self.view viewWithTag:indexPath.row + 100];
        textView.text = _detailMessageNameArr[indexPath.row];
    }

    if (indexPath.row != 0 && indexPath.row != 1 && indexPath.row != 4 && indexPath.row != 5 && indexPath.row != 7) {
        cell.detailTextLabel.text = _detailMessageNameArr[indexPath.row];
        cell.detailTextLabel.textColor = UIColorHexValue(0xB3B3B3);
        if (indexPath.row==6) {
            if (longitude>0||latitude>0) {
                cell.detailTextLabel.text = @"已定位";
            }
        }
    }
    if (indexPath.row == 2) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@", _detailMessageNameArr[2], @"    "];
        cell.detailTextLabel.textAlignment = NSTextAlignmentLeft;
    }
    cell.textLabel.text = _messageNameArr[indexPath.row];
    cell.textLabel.textColor = UIColorHexValue(0x4D4D4D);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    if (indexPath.row != 3 || indexPath.row != 7 || indexPath.row != 6) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF;
    if (indexPath.row == 3) {
        CloseAreaViewController *closeAreaVC = [[CloseAreaViewController alloc] init];
        closeAreaVC.chooseOnlyblock = ^(NSString *modelID, NSString *addressStr) {
            weakSelf.detailMessageNameArr[3] = addressStr;
            weakSelf.areaId = modelID;
            [weakSelf.factoryMessageTableView reloadData];
        };
        [self.navigationController pushViewController:closeAreaVC animated:YES];
    } else if (indexPath.row == 6) {
        FactoryMapViewController *mapVC = [[FactoryMapViewController alloc] init];
        WEAKSELF;
        mapVC.mapBlock = ^(CLLocationCoordinate2D coordinate, NSString *addressStr) {
            weakSelf.coordinate = coordinate;
            longitude = coordinate.longitude;
            latitude = coordinate.latitude;
            _detailMessageNameArr[6] = addressStr;
            _detailMessageNameArr[7] = addressStr;
            tipLabel.hidden = addressStr.length>0?YES:NO;
            [weakSelf.factoryMessageTableView reloadData];
        };
        mapVC.textFieldStr = _detailMessageNameArr[6];
        [self.navigationController pushViewController:mapVC animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

// 将点击tableviewcell的时候收回 searchBar 键盘
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    return indexPath;
}

// MARK:请求数据
- (void)saveFactoryMessage {
    UITextField *textField = [self.view viewWithTag:101];
    UITextField *textField1 = [self.view viewWithTag:104];
    UITextField *textField2 = [self.view viewWithTag:105];
    UITextField *textField3 = [self.view viewWithTag:107];
    NSString *str = [textField.text isKindOfClass:[NSNull class]] ? @"":textField.text;
    NSString *str1 = [textField1.text isKindOfClass:[NSNull class]] ? @"":textField1.text;
    NSString *str2 = [textField2.text isKindOfClass:[NSNull class]] ? @"":textField2.text;
    NSString *str3 = [textField3.text isKindOfClass:[NSNull class]] ? @"":textField3.text;
    
    if ([_detailMessageNameArr[0] isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请选择公司logo" addToView:self.view];
        return;
    }
    if ([str isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入雇主名称" addToView:self.view];
        return;
    }
    if ([_areaId isEqualToString:@""] || [_areaId isKindOfClass:[NSNull class]] || !_areaId) {
        [LTools showMBProgressWithText:@"请输入常用地" addToView:self.view];
        return;
    }
    if ([str1 isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入负责人" addToView:self.view];
        return;
    }
    if ([str2 isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入联系电话" addToView:self.view];
        return;
    }
    if ([str3 isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入联系地址" addToView:self.view];
        return;
    }
    
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
     NSDictionary *userDic = @{@"name" : str, @"headImg" : _detailMessageNameArr[0], @"area" : @{@"id" : _areaId},  @"lng" : [NSString stringWithFormat:@"%lf", _coordinate.longitude ], @"lat" : [NSString stringWithFormat:@"%lf", _coordinate.latitude]};
     NSDictionary *dic = @{@"phone" : str2, @"user" : userDic, @"linkman" : str1, @"address" : str3};
    
     [HYBaseHandler requestFactoryMessageSaveParmers:dic Success:^(id obj)
      {
          [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
          if ([obj server_Getcodecheck])
          {
              [LTools showMBProgressWithText:@"保存成功" addToView:weakSelf.view];
              dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                  [self.navigationController popViewControllerAnimated:YES];
              });
          }
          else
          {
              [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
          }
      } failed:^(NSError *error) {
          [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
          
      }];
}

- (void)requestFactoryMessage {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestFactoryInfoParmers:nil Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *dataArr = [FactoryMessageModel mj_objectArrayWithKeyValuesArray:@[obj[@"data"]]];
             FactoryMessageModel *messageModel = dataArr[0];
             
             FactoryProductModel *productModel = messageModel.product;
//             FactoryCategoryModel *catetoryModel = productModel.category;
             UserModel *userModel = messageModel.user;
             NSString *str = [userModel.province isKindOfClass:[NSNull class]] || !userModel.province ? @"" : userModel.province;
             NSString *str1 = [userModel.city isKindOfClass:[NSNull class]] || !userModel.city ? @"" : userModel.city;
             NSString *str2 = [userModel.province isKindOfClass:[NSNull class]] || !userModel.areaName ? @"" : userModel.areaName;
             _detailMessageNameArr[0] = userModel.headImg;
             _detailMessageNameArr[1] = userModel.name;
             _detailMessageNameArr[2] = userModel.mark;
             _detailMessageNameArr[3] = [NSString stringWithFormat:@"%@%@%@", str, str1, str2];
             _detailMessageNameArr[4] = messageModel.linkman;
             _detailMessageNameArr[5] = messageModel.phone;
             _detailMessageNameArr[7] = messageModel.address;
             tipLabel.hidden = messageModel.address.length>0?YES:NO;
             _areaId = userModel.areaId;
             _productId = productModel.ID;
             latitude = [userModel.lat doubleValue];
             longitude = [userModel.lng doubleValue];
             [_factoryMessageTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

// MARK:处理键盘遮住和退出键盘
// 我们获取当前tableView 的偏移量
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    /* scrollView 的偏移量*/
//    CGFloat offSetY = scrollView.contentOffset.y;
//    scrollViewOffSetY = offSetY;

}
//// 我们获取那个Cell是被点击的
//- (void)textFieldDidBeginEditing:(UITextField *)textField
//{
//    /* 获取当前cell的位置*/
//    /* 我们进行层次分析
//     * A.superview 则是 cell
//     */
//    scrollViewOffSetY = _factoryMessageTableView.contentOffset.y;
//    CGFloat Hieght = textField.superview.superview.frame.origin.y;
//    /* 获取当前点击Cell的位置*/
//    CGFloat CurrentCellY = Hieght - scrollViewOffSetY;
//    /* 获取剩余高度*/
//    CGFloat lastHeight = [UIScreen mainScreen].bounds.size.height - CurrentCellY-200;
//    remainingDistanceY = lastHeight;
//
//
//}
//// 我们在获取弹出键盘的高度和在做计算差值偏移
//-(void)jianpantanchu:(NSNotification*)Notification{
//    NSLog(@"%@",Notification);
//    /* 获取键盘的开始高度*/
//    NSDictionary *userInfo = [Notification userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    CGFloat keyBoardStart = keyboardRect.size.height;
//
//    //    CGFloat keyBoardStart = [Notification.userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue].size.height;
//    if (remainingDistanceY < keyBoardStart) {
//        /* 获取差值*/
//        CGFloat differenceValue = keyBoardStart -remainingDistanceY;
//        beforeMigrationY = differenceValue;
//        [_factoryMessageTableView setContentOffset:CGPointMake(0, differenceValue + scrollViewOffSetY) animated:YES];
//    }
//}

// 我们为了防止tableView不能返回原始没有被点击的位置(这是防止用户在键盘弹出的时候，在滑动而造成的混乱)
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /* 防止错乱停止编辑*/
    [self.view endEditing:YES];
}
// 最后键盘隐藏，返回点击前的偏移
//-(void)jianpanhuishou:(NSNotification*)Notification{
//    NSLog(@"Hide");
//    [_factoryMessageTableView setContentOffset:CGPointMake(0, scrollViewOffSetY) animated:YES];
//    beforeMigrationY = 0.0;
//}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.isEditing) {
        [textField endEditing:YES];
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        tipLabel.hidden = YES;
    } else {
        tipLabel.hidden = NO;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    _detailMessageNameArr[textField.tag - 100] = textField.text;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    _detailMessageNameArr[textView.tag - 100] = textView.text;
}

- (void)changeUserIcon {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"拍照");
        [self takePhoto];
        
    }]];
    
    //从相册中选取
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        HYLog(@"从相册中选取");
        [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"取消");
        [self dismissViewControllerAnimated:NO completion:nil];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

// MARK:系统自带相册
-(void)takePhoto
{
    //判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImageOrientation imageOrientation = image.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
    }
    _userIcon.image = image;
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HttpTool uploadImageWithPath:SERVER_PictureUpload params:nil thumbName:@"file" image:image success:^(id json)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([json server_Getcodecheck])
         {
             NSArray *dataArr = json[@"data"];
             _detailMessageNameArr[0] = dataArr[0];
         }

     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [LTools showMBProgressWithText:@"上传失败,请重试" addToView:self.view];
     } progress:^(CGFloat progress) {

     }];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
